<template>
  <div>
    <!-- 面包屑导航 -->
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <!-- 卡片视图 -->
    <section>
      <el-card>
        <div>
          <el-row :gutter="20">
            <!-- 搜索和添加区域 -->
            <el-col :span="7">
              <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" @keyup.enter.native="getUserList">
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
              </el-input>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
            </el-col>
          </el-row>
          <el-table :data="userList" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="用户名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态">
              <!-- 作用域插槽 -->
              <!-- v-slot="scope"接收当前作用域的数据 -->
              <!-- scope.row拿到这一行的数据 -->
              <template v-slot="scope">
                <el-switch v-model="scope.row.mg_state" @change="userStatueChanged(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <!-- 修改按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="small" @click="updataUser(scope.row.id)"></el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="small" @click="romoveUserById(scope.row.id)"></el-button>
                <!-- 分配按钮 -->
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false" :open-delay="300">
                  <el-button type="warning" icon="el-icon-setting" size="small" @click="setRole(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[ 4,6,8,10]" :page-size="queryInfo
          .pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </el-card>
      <!-- 添加用户的对话框 -->
      <!-- 上部区 -->
      <el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="60%" @close="DialogClosed">
        <el-form :model="addUleForm" :rules="addFormRules" ref="ruleFormRef" label-width="70px">
          <el-form-item label="用户名:" prop="username">
            <el-input v-model="addUleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input v-model="addUleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="addUleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机:" prop="mobile">
            <el-input v-model="addUleForm.mobile"></el-input>
          </el-form-item>

        </el-form>
        <!-- 下部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 上部区 -->
      <el-dialog title="修改用户信息" :visible.sync="updataDialogVisible" width="60%" @close="DialogClosed">
        <el-form :model="updataFrom" :rules="updataFormRules" ref="ruleFormRef" label-width="70px" resetFields>
          <el-form-item label="用户名:">
            <el-input v-model="updataFrom.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="updataFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机:" prop="mobile">
            <el-input v-model="updataFrom.mobile"></el-input>
          </el-form-item>

        </el-form>
        <!-- 下部区 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="updataDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click=" updataUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog title="分配角色" :visible.sync="FpJsdialogVisible" width="40%" @close="resetDialog">
        <p>用户名为：{{this.RoleInfo.username}}</p>
        <p>当前的角色为：{{this.RoleInfo.role_name}}</p>
        <p>分配新的角色：<el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in RoleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="FpJsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="JsFpInfo">确 定</el-button>
        </span>
      </el-dialog>
    </section>
  </div>
</template>

<script>
  export default {
    name: 'users',
    data () {
      // 手机自定义验证规则
      var checkMobil = (rule, value, cb) => {
        const regMobil = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (regMobil.test(value)) {
          return cb()
        }
        cb('请输入正确的手机号')
      }
      return {
        //  获取用户列表参数
        queryInfo: {
          // 查询参数
          query: '',
          // 当前页码
          pagenum: 1,
          // 每页显示条数
          pagesize: 4,
        },
        userList: [],
        //  总条目数
        total: 0,
        //  添加用户框显示于隐藏添加用户对话框
        addDialogVisible: false,
        //  修改用户框显示于隐藏用户对话框
        updataDialogVisible: false,
        //分配角色显示于隐藏对话框
        FpJsdialogVisible: false,
        // 添加用户数据
        addUleForm: {
          username: '',
          password: '',
          email: '',
          mobile: '',
          role_name: ''
        },
        //  查询的用户信息
        updataFrom: {},
        // 分配角色的用户信息数据
        RoleInfo: {},
        // 角色列表数据
        RoleList: [],
        // 以选中的角色Id值
        selectedRoleId: '',
        //表单验证规则对象
        addFormRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: checkMobil, trigger: 'blur' }
          ],
        },
        updataFormRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: checkMobil, trigger: 'blur' }
          ],
        }
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      async getUserList () {
        const { data: res } = await this.$http.get('users',
          {
            params: this.queryInfo
          })
        if (res.meta.status !== 200) return this.$message.console.error('获取用户列表失败');
        this.userList = res.data.users
        this.total = res.data.total
        // console.log(res); 
      },
      //监听每页显示条数 pageSize 改变时会触发事件
      handleSizeChange (newPage) {
        this.queryInfo.pagesize = newPage
        this.getUserList()
      },
      // 监听页码值改变的事件
      handleCurrentChange (newSize) {
        this.queryInfo.pagenum = newSize
        this.getUserList()
      },
      //  状态开关的变化
      async userStatueChanged (val) {
        //  console.log(val);
        const { data: res } = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
        //  console.log(res);
        if (res.meta.status !== 200) {
          val.mg_state = !val.mg_state
          return this.$message({
            duration: 600,
            message: '更新用户状态失败',
            type: 'error'
          });
        }
        this.$message({
          duration: 600,
          message: '更新用户状态成功',
          type: 'success'
        });
      },
      // 监听表单关闭
      DialogClosed () {
        // 清空重置表单数据
        this.$refs.ruleFormRef.resetFields()
      },

      //添加新用户
      addUser () {
        this.$refs.ruleFormRef.validate(async valid => {
          if (!valid) return
          // 发起添加用户求请
          const { data: res } = await this.$http.post('users', this.addUleForm)
          if (res.meta.status !== 201) {
            return this.$message({
              duration: 600,
              message: '添加用户失败',
              type: 'error'
            });
          }
          this.$message({
            duration: 600,
            message: '用户添加成功',
            type: 'success'
          });
          this.addDialogVisible = false
          this.getUserList()
        })
      },
      //查询用户信息
      async updataUser (id) {
        // console.log(id);
        const { data: res } = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('查询用户信息失败')
        }
        this.updataFrom = res.data
        this.updataDialogVisible = true

      },
      // 修改用户信息
      updataUserInfo () {
        this.$refs.ruleFormRef.validate(async valid => {
          if (!valid) return
          // 发起修改用户求请
          const { data: res } = await this.$http.put(`users/${this.RoleInfo.id}`, {
            email: this.updataFrom.email,
            mobile: this.updataFrom.mobile
          })
          if (res.meta.status !== 200) {
            this.$message({
              duration: 600,
              message: '修改用户信息失败',
              type: 'error'
            });
          }
          this.$message({
            duration: 600,
            message: '修改用户信息成功',
            type: 'success'
          });
          this.updataDialogVisible = false
          this.getUserList()
        })
      },
      // 根据ID删除用户信息
      async romoveUserById (id) {
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // console.log(confirmResult);
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除用户信息')
        }
        const { data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户信息失败')
        }
        this.$message.success('删除用户信息成功')
        this.getUserList()
      },
      // 分配角色对话框弹出
      async setRole (RoleInfo) {
        this.RoleInfo = RoleInfo
        // 在开展对话框之前，获取所有角色的列表
        const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message({
            duration: 600,
            message: '获取角色列表失败',
            type: 'error'
          });
        }
        this.$message({
          duration: 600,
          message: '获取角色列表成功',
          type: 'success'
        });
        this.RoleList = res.data
        this.FpJsdialogVisible = true
      },
      // 新分配角色事件
      async JsFpInfo () {
        if (!this.selectedRoleId) {
          return this.$message({
            duration: 600,
            message: '请选择要分配的角色',
            type: 'error'
          });
        }
        const { data: res } = await this.$http.put(`users/${this.RoleInfo.id}/role`, { rid: this.selectedRoleId })
        if (res.meta.status !== 200) {
          return this.$message({
            duration: 600,
            message: '分配新角色失败',
            type: 'error'
          });
        }
        this.$message({
          duration: 600,
          message: '分配新角色成功',
          type: 'success'
        });
        this.FpJsdialogVisible = false
        this.getUserList()
      },
      // 重置分配角色对话框
      resetDialog () {
        this.selectedRoleId = ''
        this.RoleInfo = ''
      }
    }
  }
</script>

<style lang="less" scoped>
p{
  font-size: 16px;
}

</style>